package com.droid.customcalendar.cal.view;

import java.util.List;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.droid.customcalendar.R;
import com.droid.customcalendar.cal.model.MonthCalendarDataGenerator;

public class DayOfWeekView extends ViewGroup {

	private static final int NR_OF_DAYS = MonthCalendarDataGenerator.NUMBER_OF_DAYS_FROM_WEEK;
	private int textColor;

	public DayOfWeekView(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DayOfWeekView, 0, 0);
		try {
			textColor = array.getColor(R.styleable.DayOfWeekView_textColor, Color.BLACK);
		} finally {
			array.recycle();
		}
		addViews();
	}

	public DayOfWeekView(Context context) {
		super(context);
		addViews();
	}

	private void addViews() {
		for (int index = 0; index < NR_OF_DAYS; index++) {
			TextView textView = createTextView();
			textView.setTextColor(textColor);
			addView(textView);
		}
	}

	protected TextView createTextView() {
		TextView textView = new TextView(getContext());
		textView.setGravity(Gravity.CENTER);
		return textView;
	}

	public void setTextColor(int color) {
		textColor = color;
		updateViews();
	}
	
	private void updateViews() {
		for (int index = 0; index < getChildCount(); index++) {
			TextView textView = (TextView) getChildAt(index);
			textView.setTextColor(textColor);
		}
	}
	
	public void setDays(List<String> days) {
		for (int index = 0; index < days.size(); index++) {
			String day = days.get(index);
			TextView textView = (TextView) getChildAt(index);
			textView.setText(day);
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int count = getChildCount();
		int width = getMeasuredWidth();
		int height = getMeasuredHeight();
		int cellWidth = width / NR_OF_DAYS;
		for (int index = 0; index < count; index++) {
			View view = getChildAt(index);
			int childWidthMS = MeasureSpec.makeMeasureSpec(cellWidth, MeasureSpec.EXACTLY);
			int childHeigthMS = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
			view.measure(childWidthMS, childHeigthMS);
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int count = getChildCount();
		int pos = 0;
		if (count > 0) {
			for (int index = 0; index < NR_OF_DAYS; index++) {
				View view = getChildAt(index);
				int width = view.getMeasuredWidth();
				view.layout(pos, 0, pos + width, view.getMeasuredHeight());
				pos += width;
			}
		}
	}

}
